﻿using Coolzon.UI.Common;
using Coolzon.UI.Common.Event.NCL;
using Coolzon.UI.Common.Event.Web;
using Coolzon.UI.Common.RealtimeProxies;
using Coolzon.UI.Common.WebProxies;
using Coolzon.UI.Core;
using Coolzon.UI.Core.Views;
using Coolzon.UI.ViewerApp.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Coolzon.UI.ViewerApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static bool isFirstReConnectWiew;
        private static bool _isFirstSetingWiew;
        private string _userAccount;
        private string _userPassword;
        private DispatcherTimer dispatcherTime;

        /// <summary>
        /// 服务器当前的Token，当加载方案后用于切换场景
        /// </summary>
        private string _serverCurrentViewToken = string.Empty;

        private bool _isClientProxyConnected;
        //private Coolzon.Event.UI.UINetConnectionStateFeedbackEvent.NetConnectionState[] clientProxyState;

        private XWindowHelper _xwindowHelper; 
        /// <summary>
        /// 鼠标移动计时器
        /// </summary>
        private DispatcherTimer _mouseHideTimer;
        /// <summary>
        /// 是否自动隐藏鼠标
        /// </summary>
        private bool _isAutoHideMouse = true;

        public MainWindow()
        {
            InitializeComponent();

            //this.Title = string.Format("可视化系统-v{0}", "2.0");//CZEnvironment.Version4);

            _isFirstSetingWiew = true;
            isFirstReConnectWiew = true;

            UIContext.Current.RootViewContainer = this._ctlViewContainer;

            #region 注册事件总线
            //Common.EventBus.Instance.Register(this);
            // 注册到事件总线上
            //Common.EventBus.Instance.Register(RemoteEventProxy.Instance);
            //NCLEventBus.Register(RemoteEventProxy.Instance);
            //CoreEventBus.Register(RemoteEventProxy.Instance);
            //WebEventBus.Register(WebEventProxy.Instance);

            NCLEventBus.Register(this);
            //UIEventBus.Register(this);
            //CoreEventBus.Register(this);
            #endregion

            LoginView loginView = new LoginView();
            loginView.Close += loginView_Close;
            UIContext.Current.RootViewContainer.SwitchView(loginView);
            loginView.Active();
            //this.PreviewKeyDown += MainWindow_PreviewKeyDown;

            #region 设置窗口的全屏状态
            //_xwindowHelper = new XWindowHelper(this);
            //if (CZEnvironment.Instance.IsFullScreen)
            //{
            //    _xwindowHelper.EnterFullscreen();
            //    UIContext.Current.IsFullScreen = true;
            //}
            //else
            //{
            //    _xwindowHelper.ExitFullscreen();
            //    UIContext.Current.IsFullScreen = false;
            //}
            #endregion

            #region 启动定时器
            //_mouseHideTimer = new DispatcherTimer();
            //this._mouseHideTimer.Tick += new EventHandler(Timer_MouseMove_Tick);
            //this._mouseHideTimer.Interval = new TimeSpan(0, 0, 1);
            //this._mouseHideTimer.Start();
            #endregion
        }

        void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //if (e.Key == Key.Enter)
            //{
            //    UIEventBus.Publish(new  UIChangeFullScreenStateEvent());
            //}
            //if (e.Key == Key.Escape)
            //{
            //    if (_settingWindow == null)
            //    {
            //        _settingWindow = new Windows.SettingWindow();
            //        _isAutoHideMouse = false;
            //        _settingWindow.Closed += _settingWindow_Closed;
            //        _settingWindow.Show();
            //    }
            //}
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
        }

        protected override void OnPreviewMouseMove(MouseEventArgs e)
        {
            //MouseMonitorHelper.UpdatePoint(e.GetPosition(this));
            base.OnPreviewMouseMove(e);
        }

        /// <summary>
        /// 检测鼠标移动计时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_MouseMove_Tick(object sender, EventArgs e)
        {
            //if (_isAutoHideMouse)
            //{
            //    if (MouseMonitorHelper.IsMouseHover())
            //    {
            //        Mouse.OverrideCursor = Cursors.None;
            //    }
            //    else
            //    {
            //        Mouse.OverrideCursor = Cursors.Arrow;
            //    }
            //}
            //else if(Mouse.OverrideCursor == Cursors.None)
            //{
            //    Mouse.OverrideCursor = Cursors.Arrow;
            //}
        }

        void loginView_Close(View view, bool isCancel)
        {
            if (!isCancel)
            {
                // 启动心跳线程
                //HeartbeatThread.Start();

                LoginView loginView = view as LoginView;
                _userAccount = loginView.UserAccount;
                _userPassword = loginView.UserPassword;
                //MessageBox.Show("OK");

                SelectSolutionView selectSolutionView = new SelectSolutionView();
                selectSolutionView.Close += selectSolutionView_Close;
                UIContext.Current.RootViewContainer.SwitchView(selectSolutionView);
                //selectSolutionView.Active();
            }
        }

        void selectSolutionView_Close(View view, bool isCancel)
        {
            if (!isCancel)
            {
                SelectSolutionView selectSolutionView = view as SelectSolutionView;

                // 进入方案加载界面，停止重新建立连接的线程
                //ReconnectThread.Stop();

                LoadingView loadingView = new LoadingView(selectSolutionView.SelectedSolutionName,
                    Config.GetSolutionFile(selectSolutionView.SelectedSolutionName),
                    Config.GetSolutionDirectory(selectSolutionView.SelectedSolutionName));
                loadingView.Close += loadingView_Close;
                loadingView.LoadSolutionErrorEvent += LoadingView_LoadSolutionErrorEvent;
                UIContext.Current.RootViewContainer.SwitchView(loadingView);
                //loadingView.Active();
            }
        }

        /// <summary>
        /// 加载方案出错事件
        /// </summary>
        /// <param name="errorMessage"></param>
        private void LoadingView_LoadSolutionErrorEvent(string errorMessage)
        {
            MessageBox.Show("加载方案出错");
            ////开启重连线程，加载出错时也跳转到WaitingView
            //ReconnectThread.Start();
            //// 显示加载方案出错的界面，并开启重连线程
            //CPPEI.Coolzon.UI.Views.WaitingView waitingView = new UI.Views.WaitingView();
            //waitingView.Close += waitingView_Close;
            //UIContext.Current.RootViewContainer.SwitchView(waitingView);
            //waitingView.Active();
        }

        void loadingView_Close(View view, bool isCancel)
        {
            LoadingView loadingView = view as LoadingView;
            Coolzon.UI.ViewerApp.Views.RenderView renderView = new Coolzon.UI.ViewerApp.Views.RenderView(loadingView.LoadedSolution);
            UIContext.Current.RenderView = renderView;

            ////Common.Logger.Debug("设置显示模式为水平拉伸");
            ////renderView.SetDisplayMode(PartFrameDisplayMode.HStretch);

            //// 将事件远程处理模式的代理实例注册到事件总线上
            //RemoteEventProxy.Instance.SetRenderView(renderView);
            //// 注册到网络的事件总线上
            //Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Register(this);
            //Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Register(renderView);

            //renderView.Close += renderView_Close;
            UIContext.Current.RootViewContainer.SwitchView(renderView);
            //renderView.Background = new SolidColorBrush(Colors.Black);
            //renderView.Active();

            ////正在加载方案设置成false
            //UIContext.Current.IsLoadingSolution = false;

            ////通知服务器已恢复正常状态
            //Coolzon.Event.NCL.NCLUpdateClientStatusEvent @eventNormal = new Coolzon.Event.NCL.NCLUpdateClientStatusEvent(Service.Contract.ClientStatus.Normal);
            //Coolzon.Event.NCL.NCLEventBus.PublishAsync(@eventNormal);

            //// 启动展示视图同步线程
            //if (!string.IsNullOrWhiteSpace(_serverCurrentViewToken))
            //{
            //    SyncViewStateThread.Start(renderView, _serverCurrentViewToken); _serverCurrentViewToken = "";
            //}

            //// 启动重新建立连接的线程
            //ReconnectThread.Start();
        }
        /*
        void waitingView_Close(View view, bool isCancel)
        {
            if (!isCancel)
            {
                CPPEI.Coolzon.UI.Views.WaitingView waitingView = view as UI.Views.WaitingView;
                _serverCurrentViewToken = waitingView.ViewStateToken;

                ReconnectThread.Stop();
                CPPEI.Coolzon.UI.Views.LoadingView loadingView = new UI.Views.LoadingView(waitingView.SelectedSolutionName,
                    CZEnvironment.GetSolutionFilePath(waitingView.SelectedSolutionName),
                    CZEnvironment.GetSolutionDirectoryPath(waitingView.SelectedSolutionName));
                loadingView.Close += loadingView_Close;
                loadingView.LoadSolutionErrorEvent += LoadingView_LoadSolutionErrorEvent;
                UIContext.Current.RootViewContainer.SwitchView(loadingView);
                loadingView.Active();
            }
        }

        /// <summary>
        /// 加载方案出错事件
        /// </summary>
        /// <param name="errorMessage"></param>
        private void LoadingView_LoadSolutionErrorEvent(string errorMessage)
        {
            //开启重连线程，加载出错时也跳转到WaitingView
            ReconnectThread.Start();
            // 显示加载方案出错的界面，并开启重连线程
            CPPEI.Coolzon.UI.Views.WaitingView waitingView = new UI.Views.WaitingView();
            waitingView.Close += waitingView_Close;
            UIContext.Current.RootViewContainer.SwitchView(waitingView);
            waitingView.Active();
        }

        void loadingView_Close(UI.View view, bool isCancel)
        {
            UI.Views.LoadingView syncView = view as UI.Views.LoadingView;
            CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;

            //Common.Logger.Debug("设置显示模式为水平拉伸");
            //renderView.SetDisplayMode(PartFrameDisplayMode.HStretch);

            // 将事件远程处理模式的代理实例注册到事件总线上
            RemoteEventProxy.Instance.SetRenderView(renderView);
            // 注册到网络的事件总线上
            Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Register(this);
            Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Register(renderView);

            renderView.Close += renderView_Close;
            UIContext.Current.RootViewContainer.SwitchView(renderView);
            renderView.Background = new SolidColorBrush(Colors.Black);
            renderView.Active();

            //正在加载方案设置成false
            UIContext.Current.IsLoadingSolution = false;

            //通知服务器已恢复正常状态
            Coolzon.Event.NCL.NCLUpdateClientStatusEvent @eventNormal = new Coolzon.Event.NCL.NCLUpdateClientStatusEvent(Service.Contract.ClientStatus.Normal);
            Coolzon.Event.NCL.NCLEventBus.PublishAsync(@eventNormal);

            // 启动展示视图同步线程
            if (!string.IsNullOrWhiteSpace(_serverCurrentViewToken))
            {
                SyncViewStateThread.Start(renderView, _serverCurrentViewToken); _serverCurrentViewToken = "";
            }

            // 启动重新建立连接的线程
            ReconnectThread.Start();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            HeartbeatThread.Stop();
            ReconnectThread.Stop();
            SwitchMainServerThread.Stop();
            OpenDefaultSceneThread.Stop();

            if(UIContext.Current.RootViewContainer.CurrentView != null)
            {
                UIContext.Current.RootViewContainer.CurrentView.Destory();
            }

            base.OnClosing(e);
        }

        void MainWindow_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            //if (e.LeftButton == MouseButtonState.Pressed)
            //{
            //    CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
            //    _hLoopOffset += 10;
            //    renderView.HLoop(_hLoopOffset);
            //}
            //else if(e.RightButton == MouseButtonState.Pressed)
            //{
            //    CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
            //    _hLoopOffset -= 10;
            //    renderView.HLoop(_hLoopOffset);
            //}
        }

        double _hLoopOffset = 0;

        void renderView_Close(UI.View view, bool isCancel)
        {
        }
        void dispatcherTime_Tick(object sender, EventArgs e)
        {
            dispatcherTime.IsEnabled = false;
            CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
            OpenNextDisplayflowNode(renderView.CurrentScene);
        }
        private void OpenNextDisplayflowNode(Scene scene)
        {
            DisplayflowNode currentDisplayflowNode = GetDispayflowNodeBySceneName(scene);
            if (currentDisplayflowNode == null)
            {
                // 为发现此节点，返回第一个节点
                NCLEventBus.Publish(new NCLOpenSceneEvent(SwitchMode.Replace, "", UIContext.Current.Solution.Displayflow.Nodes[0].SceneName, null));
                return;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(currentDisplayflowNode.NextName))
                {
                    NCLEventBus.Publish(new NCLOpenSceneEvent(SwitchMode.Replace, "", currentDisplayflowNode.NextName, null));
                }
                else
                {
                    Common.Logger.ErrorToTag("UI", "{0}未发现下一个场景", currentDisplayflowNode.SceneName);
                }
            }
        }

        private DisplayflowNode GetDispayflowNodeBySceneName(Scene scene)
        {
            if (UIContext.Current.Solution.Displayflow == null) return null;
            for (int index = 0; index < UIContext.Current.Solution.Displayflow.Nodes.Count; index++)
            {
                DisplayflowNode dfn = UIContext.Current.Solution.Displayflow.Nodes[index];
                if (dfn.SceneName.Equals(scene.Name))
                {
                    return dfn;
                }
            }
            return null;
        }

        private void NextDisplayflowNode(DisplayflowNode currentDisplayflowNode)
        {
            int index = 0;
            for (; index < UIContext.Current.Solution.Displayflow.Nodes.Count; index++)
            {
                DisplayflowNode displayflowNode = UIContext.Current.Solution.Displayflow.Nodes[index];
                if (displayflowNode.SceneName.Equals(currentDisplayflowNode.SceneName))
                {
                    break;
                }
            }
            DisplayflowNode displayflownode = UIContext.Current.Solution.Displayflow.Nodes[index + 1];
            if (displayflownode == null)
            {
                displayflownode = UIContext.Current.Solution.Displayflow.Nodes[index - 1];
            }
            if (displayflownode != null)
            {
                NCLEventBus.Publish(new NCLOpenSceneEvent(SwitchMode.Replace, "", displayflownode.SceneName, null));
            }
        }

        

        void reConnectView_Close(UI.View view, bool isCancel)
        {
            isFirstReConnectWiew = true;
        }
*/
        private void _ctlViewContainer_MouseMove(object sender, MouseEventArgs e)
        {
            //显示鼠标
            if (Mouse.OverrideCursor != Cursors.Arrow)
            {
                Mouse.OverrideCursor = Cursors.Arrow;
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("您是否要退出可视化系统?", "退出确认", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                e.Cancel = true;
            base.OnClosing(e);
        }
    }
}
